<?php

namespace App\Http\Controllers\Bus;

use App\Http\Controllers\Controller;
use App\Models\Bus\Bus;
use App\Models\Bus\BusIsCheck;
use Illuminate\Http\Request;

class BusIsCheckController extends Controller
{
    /**
     * 车辆列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function busIsCheckList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $data = $this->getBusIsCheckList($params)->orderBy('bus_id')->orderByDesc('month')->get()->toArray();
        if ($data) {
            $data = $this->transData($data);
        }
        $dataCount = $this->getBusIsCheckList($countParams)->count();

        return response()->formatJson(['personnel' => $data, 'count' => $dataCount]);
    }

    public function getBusIsCheckList($params): \Illuminate\Database\Eloquent\Builder
    {
        $ids = [];
        if (isset($params['license_plate_num'])) {
            $ids = Bus::query()->select('id')
                ->where('license_plate_num', 'like', '%'.$params['license_plate_num'].'%')
                ->orderBy('id')
                ->pluck('id')
                ->toArray();
        } else {
            $ids = Bus::query()->select('id')->orderBy('id')->pluck('id')->toArray();
        }

        $query = BusIsCheck::query()->with('bus');

        if ($ids) {
            $query->whereIn('bus_id', $ids);
        }

        if (isset($params['month'])) {
            $query->where('month', $params['month'].'-01');
        }

        if (isset($params['pageNumber'], $params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query;
    }

    public function transData($data)
    {
        foreach ($data as $key => $bus) {
            foreach ($bus as $filed => $value) {
                if ($filed === 'bus') {
                    $data[$key]['license_plate_num'] = $value['license_plate_num'];
                }
                $data[$key]['edit'] = false;
            }
        }

        return $data;
    }

    /**
     * 修改车辆信息
     *
     * @param  Request  $request
     * @param           $id
     *
     * @return mixed
     */
    public function update(Request $request, $id)
    {
        $params = $request->all();
        $bus = BusIsCheck::query()->find($id);
        $result = $bus->update(['is_check' => $params['is_check']]);
        $message = $result ? '修改成功' : '修改失败';

        return response()->formatJson($result, $message);
    }
}
